package com.ctyon.watchmanager.ui.fragment;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.ctyon.common.util.DataUtil;
import com.ctyon.common.util.GsonUtil;
import com.ctyon.common.util.SPUtils;
import com.ctyon.common.util.TSnackbarUtil;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.databinding.FragmentLoginBinding;
import com.ctyon.watchmanager.listener.ItemClickListener;
import com.ctyon.watchmanager.model.db.entity.LoginHistoryEntity;
import com.ctyon.watchmanager.model.db.entity.ex.LoginHistory;
import com.ctyon.watchmanager.model.net.entity.Manager;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.ctyon.watchmanager.ui.adapter.LoginHistoryAdapter;
import com.ctyon.watchmanager.bean.LoginBean;
import com.ctyon.watchmanager.present.LoginPresenter;
import com.ctyon.watchmanager.viewmodel.LoginViewModel;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;

import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.ctyon.common.container.ARouterPath.ROUTER_ACTIVITY_CONTAINER;
import static com.ctyon.common.container.ARouterPath.ROUTER_ACTIVITY_MAIN;
import static com.ctyon.common.util.SPUtils.ACCOUNT_IMG;
import static com.ctyon.common.util.SPUtils.ACCOUNT_NUMBER;
import static com.ctyon.common.util.SPUtils.ACCOUNT_PASSWORD;
import static com.ctyon.common.util.SPUtils.IS_LOGIN;
import static com.ctyon.watchmanager.config.OssConfig.endpoint;
import static com.ctyon.watchmanager.config.OssConfig.picture;
import static com.ctyon.watchmanager.ui.activity.ContainerActivity.TAB_INDEX_PARAM;

/**
 * CreateDate：19-6-25 on 上午9:13
 * Describe:
 * Coder: lee
 */
public class LoginFragment extends BaseFragment {

    public static final String TAG = "LoginFragment";

    private LoginViewModel mViewModel;
    private FragmentLoginBinding mBinding;
    private LoginHistoryAdapter mAdapter;
    private CountDownTimer countDownTimer;
    private LoginBean loginBean;
    private String cover;

    public static LoginFragment newInstance() {
        final LoginFragment fragment = new LoginFragment();
        final Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_login, container, false);

        mBinding.setHistoryShow(false);
        mBinding.setCleanShow(false);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mAdapter = new LoginHistoryAdapter(itemClickListener);
        mBinding.loginHistoryRecycle.setLayoutManager(layoutManager);
        mBinding.loginHistoryRecycle.setAdapter(mAdapter);

        mBinding.setLoginPresenter(presenter);

        return mBinding.getRoot();

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (mBinding.getHistoryShow()) {
            mBinding.setHistoryShow(false);
        }
        String number = SPUtils.getInstance().getString(ACCOUNT_NUMBER);
        String password = SPUtils.getInstance().getString(ACCOUNT_PASSWORD);
        loginBean = new LoginBean();
        if (!DataUtil.isEmptyOr(number, password)) {
            loginBean.setPhoneNumber(number);
            loginBean.setPassword(password);
        }
        mBinding.setLoginBean(loginBean);
        cover = SPUtils.getInstance().getString(ACCOUNT_IMG);
        mBinding.setCover(cover);
        mViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
        subscribeHistory(mViewModel.getmObservableHistories());
    }

    private void subscribeHistory(LiveData<List<LoginHistoryEntity>> liveData) {
        // Update the list when the data changes
        liveData.observe(this, (loginHistories) -> {
            if (loginHistories != null && loginHistories.size() > 0) {
                mAdapter.setLoginHistoryList(loginHistories);
                if (!mBinding.getHistoryAble()){
                    mBinding.setHistoryAble(true);
                }
            }
            // espresso does not know how to wait for data binding's loop so we execute changes
            // sync.
            mBinding.executePendingBindings();
        });
    }

    private final LoginPresenter presenter = new LoginPresenter() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            Log.d("Lee_Login", "onFocusChange : hasFocus = " + hasFocus);
            if (!hasFocus) {//phone EditText输入框失去焦点
                mBinding.setHistoryShow(false);
            } else {
                if (!DataUtil.isEmptyOr(loginBean.getPhoneNumber())) {
                    mBinding.phone.setSelection(loginBean.getPhoneNumber().length());
                }
            }
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.d("Lee_Login", "onTextChanged : s = " + s);
            if (mBinding.getCleanShow() && s.toString().equals("")) {
                mBinding.setCleanShow(false);
                mBinding.password.setText("");
                mBinding.setCover("");
            } else if (!mBinding.getCleanShow() && !s.toString().equals("")) {
                mBinding.setCleanShow(true);
            }
        }

        @Override
        public void onLoginButtonClick() {
            if (mBinding.getIsRegister()) {
                NetService.getInstance()
                        .register(loginBean.getRegisterPhoneNumber(), loginBean.getRegisterPassword(), loginBean.getRegisterCode())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<BaseResponseEntity>() {
                            @Override
                            public void onSuccess(BaseResponseEntity responseEntity) {
                                Logger.t(LTAG).d("onSuccess : " + responseEntity.toString());
                                TSnackbarUtil.TSBSuccess(getActivity(), "注册成功");
                                loginBean.setPassword("");
                                loginBean.setRegisterPhoneNumber("");
                                loginBean.setRegisterPassword("");
                                loginBean.setRegisterCode("");
                                mBinding.phone.setText(loginBean.getRegisterPhoneNumber());
                                mBinding.password.setText(loginBean.getRegisterPassword());
                                mBinding.setIsRegister(false);
                            }
                        });
            } else {
                String userName = mBinding.getLoginBean().getPhoneNumber();
                String password = mBinding.getLoginBean().getPassword();
                Log.d("Lee_Login", "onLoginButtonClick :   userName = " + userName + "  password = " + password);
                NetService.getInstance()
                        .login(loginBean.getPhoneNumber(), loginBean.getPassword())
                        .timeout(5, TimeUnit.SECONDS)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new BaseObserver<BaseResponseEntity>(getActivity(), true) {
                            @Override
                            public void onSuccess(BaseResponseEntity responseEntity) {
                                Logger.t(LTAG).d("onSuccess : " + responseEntity.toString());
                                Observable.create((ObservableOnSubscribe<Manager>) emitter -> {
                                    Logger.t(LTAG).d("format data");
                                    String data = responseEntity.data.toString();
                                    if (data.contains("=")) {
                                        data = data.replace("=", ":");
                                    }
                                    Manager manager = GsonUtil.getGsonInstance().fromJson(data, Manager.class);
                                    manager.setImg(endpoint.replace("http://", "https://ctyon.") + "/" + picture + manager.getPhoneNumber() + ".png");
                                    mViewModel.insertHistory(manager);
                                    BasicApp.getInstance().setManager(manager);
                                    SPUtils.getInstance().put(IS_LOGIN, true);
                                    SPUtils.getInstance().put(ACCOUNT_NUMBER, manager.getPhoneNumber());
                                    SPUtils.getInstance().put(ACCOUNT_PASSWORD, manager.getPassword());
                                    SPUtils.getInstance().put(ACCOUNT_IMG, manager.getImg());
                                    MobclickAgent.onProfileSignIn(manager.getPhoneNumber());
                                    emitter.onNext(manager);
                                })
                                        .subscribeOn(Schedulers.newThread())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(manager -> {
                                            Logger.t(LTAG).d("aRouter");
                                            //当用户使用自有账号登录时，可以这样统计：
                                            ARouter.getInstance().build(ROUTER_ACTIVITY_MAIN).navigation();
                                            getActivity().finish();
                                        });
                            }
                        });
            }

        }

        @Override
        public void onShowHistoryClick() {
            mBinding.setHistoryShow(!mBinding.getHistoryShow());
            if (mBinding.getHistoryShow()) {
                mBinding.phone.requestFocus();
            }
        }

        @Override
        public void onRetrieveClick() {//找回密码
            ARouter.getInstance().build(ROUTER_ACTIVITY_CONTAINER)
                    .withString(TAB_INDEX_PARAM, RetrieveFragment.TAG)
                    .navigation();
        }

        @Override
        public void onSingInClick() {//注册
            if (!mBinding.getIsRegister()) {
                mBinding.setIsRegister(true);
                mBinding.setCover("");
            }
        }

        @Override
        public void onSingUpClick() {//登陆
            if (mBinding.getIsRegister()) {
                mBinding.setIsRegister(false);
                mBinding.setCover(cover);
            }
        }

        @Override
        public void onCodeClick() {
            Log.d("Lee_Login", "onCodeClick");
            String phone = loginBean.getRegisterPhoneNumber();
            Logger.t(LTAG).d("phone : " + phone);
            if (!DataUtil.checkPhone(phone)){
                TSnackbarUtil.TSBError(getActivity(), "请输入正确手机号");
                return;
            }
            final String method = "getCode";
            if (NetService.getInstance().isDisable(method)) {
                TSnackbarUtil.TSBError(getActivity(), "请稍候...");
                return;
            }

            NetService.getInstance()
                    .getCode(phone)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<BaseResponseEntity>() {
                        @Override
                        public void onSuccess(BaseResponseEntity responseEntity) {
                            Logger.t(LTAG).d("onSuccess : " + responseEntity.toString());
                            TSnackbarUtil.TSBSuccess(getActivity(), "短信已发送");
                            if (null == countDownTimer) {
                                initCountDown();
                            }
                            if (mBinding.getCountDown() == null) {
                                countDownTimer.start();
                            }
                        }
                        @Override
                        public String onOver() {
                            return method;
                        }
                    });
        }

        @Override
        public void onCleanClick() {
            mBinding.phone.setText("");
            mBinding.password.setText("");
            mBinding.setCover("");
        }

    };

    private final ItemClickListener<LoginHistory> itemClickListener = (history) -> {
        Logger.t(LTAG).d(history);
        mBinding.phone.setText(history.getUserName());
        mBinding.password.setText(history.getPassword());
        mBinding.phone.clearFocus();
        cover = history.getUserImgUrl();
        mBinding.setCover(cover);
    };

    private void initCountDown() {
        countDownTimer = new CountDownTimer(30000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mBinding.setCountDown(millisUntilFinished / 1000 + "s");
            }

            @Override
            public void onFinish() {
                mBinding.setCountDown(null);
            }
        };
    }

}
